package org.example.fancystudy.atomics;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * @author chaigq
 * @version 1.0
 * @date 2023/2/20 10:38
 */
//资源类
class BankAccount{
    String bankName = "CCB";
    //更新的对象属性必须使用 public volatile 修饰符。
    public volatile int money = 0;
    // 因为对象的属性修改类型原子类都是抽象类，所以每次使用都必须
    // 使用静态方法newUpdater()创建一个更新器，并且需要设置想要更新的类和属性。
    AtomicIntegerFieldUpdater<BankAccount> fieldUpdater =
            AtomicIntegerFieldUpdater.newUpdater(BankAccount.class, "money");
    public void setFieldUpdater(BankAccount bankAccount){
        fieldUpdater.getAndIncrement(bankAccount);
    }
}
public class AtomicIntegerFieldUpdaterDemo {
    public static void main(String[] args) throws InterruptedException {
        BankAccount bankAccount = new BankAccount();
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                try {
                    bankAccount.setFieldUpdater(bankAccount);
                }finally {
                    countDownLatch.countDown();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t"+"result: "+bankAccount.money);
    }
}
